import React,{useState,useEffect} from 'react'
import {List,Row,Col,Button,Modal, message} from 'antd'
import { getArticleListURL , removeArticleURL} from '../../utils/api'
import { sendActionGet } from '../../utils/axios'
import moment from 'moment'

const ArticleList=(props)=>{
    const [list,setList] = useState()

    useEffect(()=>{
        getArticleList()
    },[])

    const getArticleList=async()=>{
        const res = await sendActionGet(getArticleListURL)
        console.log('文章列表',res.data.data)
        setList(res.data.data)
    }

    const checkRemoveArticle=(id)=>{
        Modal.confirm({
            content:'确认删除',
            onOk:()=>{
                removeArticle(id)
            }
        })
    }

    const removeArticle=async(id)=>{
        const res = await sendActionGet(removeArticleURL+`/${id}`)
        if(res.data.data.affectedRows===1){
            message.success('删除成功')
            getArticleList()
        }else{
            message.error('删除失败')
        }
    }

    const toUpdateArticle=(id)=>{
        props.history.push(`/index/updateArticle/${id}`)
    }

    return(
        <div>
            <List header={
                <Row style={{textAlign:'center'}}>
                    <Col span={8}>文章标题</Col>
                    <Col span={8}>发布时间</Col>
                    <Col span={8}>操作</Col>
                </Row>
            }
            bordered
            dataSource={list}
            itemLayout="vertical"
            renderItem={(item)=>(
                <List.Item>
                <Row style={{textAlign:"center"}}>
                    <Col span={8}>{item.title}</Col>
                    <Col span={8}>{moment(item.addTime).format('YYYY-MM-DD')}</Col>
                    <Col span={8}>
                    <Row justify='center'>
                    <Col span={5}><Button type="primary" onClick={()=>{toUpdateArticle(item.id)}}>修改文章</Button></Col>

                    <Col span={5}><Button danger onClick={()=>{checkRemoveArticle(item.id)}}>删除文章</Button></Col>
                    </Row>
                    </Col>
                </Row>
                </List.Item>
            )}
            />
        </div>
    )
}

export default ArticleList